<template>
    <div>
        <el-upload class="upload-demo" :action="url + 'upload/'" :data="{ group: this.group }" :on-success="handleSuccess"
            :file-list="fileList" :auto-upload="true" :on-remove="handleRemove" :limit="20" :on-exceed="handleExceed"
            :on-preview='openFile' :show-file-list="true" :before-upload="beforeUpload" :on-error="handleError" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">支持md,txt,pdf,docx,xls,xlsx文件，且不超过10M</div>
        </el-upload>
        <!--                <el-button @click="downloadFile(fileToDownload)">下载文件</el-button>-->
    </div>
    <!--                :before-upload="beforeUpload"-->
</template>

<script>
import axios from 'axios';
import { get_filelist,del_file } from "@/apis/file";
import setting from '@/setting'

export default {
    name: "file",
    data() {
        return {
            url: setting.BaseUrl,
            fileList: [],
            messages: [], 
            fileToDownload: null,
            group: '',
        };
    },
    beforeMount() {
        this.bus.$on("group", group => {
            this.group = group['id']
            console.log('file', group['id'])
            this.fileList = []
            get_filelist(group['id']).then(ret => {
                ret.forEach(file => {
                    this.fileList.push({
                        id: file.id,
                        name: file.file_name,
                        size: file.file_size,
                        url: file.file,
                    })
                })
            })
        });
    },
    methods: {
        openFile(e) { // 点击上传的文件列表的文件的操作
            console.log(e, "点击上传的文件列表的文件的操作");
            window.open(this.url + e.url);
            // var a = document.createElement("a");
            // console.log(a, "创建a");
            // var event = new MouseEvent("click");
            // a.target = "_blank";
            // a.download = e.name;
            // a.href = this.url+e.url;//路径前拼上前缀，完整路径
            // a.dispatchEvent(event);
        },
        beforeUpload(file) {
            const isLt10M = file.size / 1024 / 1024 < 10;
            const type = file.name.split('.').pop().toLowerCase();
            const types = ['md', 'txt', 'pdf', 'docx', 'xls', 'xlsx'];
            if (!isLt10M) {
                this.$message.error('上传文件大小不能超过 10MB!');
                return false;
            }
            if (types.indexOf(type) === -1) {
                this.$message.error('上传文件只能是md,txt,pdf,docx,xls,xlsx格式!');
                return false;
            }
            return true;
        },
        handleError(err, file, fileList) {
            this.$message.error(`上传文件 "${file.name}" 失败`);
        },
        handleSuccess(response, file, fileList) {
            this.$message({
                message: '上传成功',
                type: 'success',
            });

            // 假设后端返回的文件信息包含文件ID，我们将其保存下来用于下载
            this.fileToDownload = response.id;

            // 更新文件列表，可能需要包含更多信息，如文件名、大小等
            this.fileList.push({
                id: response.fileid,
                name: response.filename,
                size: response.size,
                url: response.url,
            })
            console.log(this.fileList)
        },

        handleRemove(file,fileList) {

            console.log('group id:',this.group);
            console.log('file id:',file.id);
            let id = this.group;


            del_file(id, file.id)
                .then(response => {  // 将 res 改为 response
                    // 删除成功后，从 fileList 中移除该文件,并将数据同步给事件总线

                    this.fileList = this.fileList.filter(item => item !== file);
                    // this.bus.$emit('file-removed', this.fileList);
                //     this.fileList=[];
                //     response.forEach(file => {
                //     this.fileList.push({
                //         name: file.file_name,
                //         size: file.file_size,
                //         url: file.file,
                //     })
                // })

                })
                .catch(err => {
                    console.error(err);
                    this.$message.error('删除文件失败');
                });

            console.log(file, fileList);
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },

    },
};
</script>

<style scoped>
.upload-demo {
    width: 360px;
    min-height: 180px;
    text-align: left;
    border-radius: 6px;
    cursor: pointer;
}

.upload-demo:hover {
    border-color: #409EFF;
}

.el-upload__tip {
    color: #999;
    font-size: 12px;
    text-align: left;
}
</style>

